<?php
namespace app\controller;

use app\BaseController;
use QL\QueryList;
use think\facade\View;

class Collect extends BaseController
{
    public function index()
    {
        $url = $this->request->param("link");
        $QueryList = new QueryList();
        $content = $QueryList->get($url);

        $a = $content->find('a')->attrs('href');

        return json_encode(["code"=>0,"msg"=>"获取成功","data"=>$a->all()]);
    }

    public function copy()
    {
        $url = $this->request->param("link");

        $QueryList = new QueryList();
        $content = $QueryList->get($url);

        $script = $content->find('script')->attrs('src');
        $link = $content->find('link')->attrs('href');
        $img = $content->find('img')->attrs('src');

        $urls = $script->all() + $link->all() + $img->all();

        return json_encode(["code"=>0,"msg"=>"获取成功","data"=>$urls]);
    }

    public function down()
    {
        $url = $this->request->param("link");
        $project = $this->request->param("project",'','strip_tags');

        $pathUrl = parse_url($url);
        $filepath = dirname($pathUrl["path"]);
        $filepath = str_replace('//','/',$filepath);
        $filepath = substr($filepath,1,strlen($filepath));

        $filename = basename($pathUrl["path"]);
        echo "<pre>";
        print_r($pathUrl);
        echo "</pre>";
        die;
        if(empty($filename)){
            $filename = 'index.html';
        }

        $path = str_replace('/','',$project);
        $path = str_replace('.','',$path);
        $path = '/static/templates/'.str_replace(':','',$path);

        $path = dirname($this->request->server("SCRIPT_FILENAME")).$path.'/'.$filepath;
        $path = str_replace('//','/',$path);

        if(!file_exists(dirname($path,1))){
            mkdir($path,0664,1);
        }

        $data = file_get_contents($url);
        $result = file_put_contents($path."/".$filename,$data);

        $data = ["oldpath"=>$url,"newpath"=>$filepath];

        return json_encode(["code"=>0,"msg"=>"获取成功",$data]);

    }
}
